#!/bin/bash

if [[ -z "$METIS_HOME" ]]; then
	echo "The METIS_HOME environment variable has not been set."
	echo "This is the directory where metis.sh and metis.config are stored"
	exit 1
fi

source "$METIS_HOME"metis.config

if [[ $EUID -ne 0 ]]; then
	echo "Pentest.sh must be run as the root user"
	exit 1
fi

echo $$ > $procID

noscript=false
escalateMode='none'
escalateModeSelected=false
customScanModeSelected=false
discoverModeSelected=false
pluginsEnabled=false

usage() {	
	echo	
	echo	"--------"
	echo	"Overview"
	echo	"--------"	
	echo
	echo	"Metis can be used to initiate an infrastructure pentest against the specified targets file."
	echo	"It provides the following features; "
	echo 	"	- Initiate various phases of NMAP scans in arbitary sequences"
	echo	"	- Parse output of NMAPs into an sqlite database"
	echo	"	- Automatically outputs scan results to CSV"
	echo	"	- Automatically outputs scan summary files"
	echo	"	- Extremely simple plugin architecture to automatically query the database initiate "
	echo 	"	  tools against groups of specific hosts or services"
	echo	"	- configurable live host discovery mode that can be used to identify live hosts before"
	echo 	"	  perform full scans against hosts"
	echo
	echo	"The pentest configuration file should be located at \${METIS_HOME}/metis.config"
	echo	"The environment variable METIS_HOME must be set and is required by a number of scripts."
	echo 	"It should specify the folder where metis.sh and metis.config are located."
	echo
	echo	"--------------------"
	echo	"Command Line Options"
	echo	"--------------------"
	echo
	printf	'%s-n\n'
	echo	"	Don't run any nmap scripts with the full tcp scans."
	echo
	echo	"-s <scan-order>"
	echo	"	Specify the scan order (e.g. -s 8,9,2,3,6,7). Scans are completed in the order specified."
	echo	"	1 - Shotgun tcp"
	echo	"	2 - Fast tcp"
	echo	"	3 - Default tcp"
	echo	"	4 - Full tcp"
	echo	"	5 - Shotgun udp"
	echo	"	6 - Fast udp"
	echo	"	7 - Default udp"
	echo	"	8 - ICMP ping"
	echo	"	9 - rDNS"
	echo 
	echo	"-e [ shotgun | fast | default | local ]"
	echo	"	Specify escalate scan mode. Performs one round of scans, using this info it determines if a host is" 
	echo	"	up, if it is identified as up, a second round of scanning is performed against the IP:"
	echo
	echo	"	shotgun	= ROUND 1: Shotgun TCP, Shotgun UDP, rDNS, ICMP echo"
	echo	"		  ROUND 2: Full TCP, Default UDP" 
	echo 	"	fast 	= ROUND 1: Fast TCP, Shotgun UDP, rDNS, ICMP echo"
	echo	"		  ROUND 2: Full TCP, Default UDP"
	echo	"	default	= ROUND 1: Default TCP, Fast UDP, rDNS, ICMP echo" 
	echo	"		  ROUND 2: Full TCP, Default UDP"
	echo	"	local	= ROUND 1: ARP sweep of local subnet"
	echo	"		  ROUND 2: Full TCP, Default UDP"
	echo
	echo	"-I <interface>"
	echo	"	If using the 'local' escalator mode (e.g. -e local), then the interface must be specified, (e.g. -I eth1)"
	echo
	echo	"-l"
	echo	"	Live host discovery mode; identifies hosts through; ICMP echo, rDNS, shotgun TCP/UDP scans." 
	echo	"	Outputs live IP's to hosts.alive.unique. No further scanning is performed."
 	echo
	echo	"-P"
	echo	"	Execute plugins that are contained within the active directory, if no scan types" 
	echo	"	are specified plugins will run against the database defined in metis.config."
	echo
	echo	"-t <max-plugin-timeout>"
	echo	"	Timeouts for the Metis plugins are configured on a per-plugin basis. However, you can override"
	echo	"	the indivudal maximum timeouts by specifying this value. Value should be specified in seconds."
	echo	"	Only has an affect when used in conjunction with the -P option" 
	echo
	echo	"-------------"
	echo	"Configuration"
	echo	"-------------"
	echo	""
	echo	"The config file (metis.config) is used to specify a number of settings such as;"
	echo	"	- Input/Output Configuration"
	echo	"	- Script Setup/Configuration"
	echo	"	- Scanning Option Configuration"
	echo	
	echo	"You will likely only ever need to make changes near to the top of the configuration file."
	echo
	echo	"Input/Output Configuration:"
	echo	"These variables are used by the scripts for specifying the input target file as well as various"
	echo	"output locations and filenames."
	echo 
	echo 	"Script Setup/Configuration:"
	echo	"These variables are used to specify the various locations of scripts and tools used."
	echo
	echo	"Scanning Option Configuration:"
	echo	"These variables are used to specify the various scanning options, at the moment these configure"
	echo	"the level of scanning aggression. The current options available are, speed, and threads. The speed"
	echo	"relates to the NMAP -T option, and should use the same format (e.g. T4)."
	echo	"The threads option (which is actually more multiprocessing than multithreading) relates to the"
	echo	"number of concurrent nmaps. The number of concurrent processes for Metis plugins (-P option)"
	echo	"should be specified in the specific plugin."
	echo
	exit
}

function execFastTCP() {
	echo 0 >  "$scanCounter"
	echo "---------------------------------------------------------------------"
	echo "+ Setting off fast TCP scan @" `date`
	echo "---------------------------------------------------------------------"
	echo -n "Completed scans for: 0/${targetCount}"
	cat ${targetList} | xargs -P "$threads" -i /bin/bash -c "${scanScriptDirectory}scan_tcp_fast.sh -h {} -f -s ${speed} -o ${nmapOutputDir} -l ${loggingDir} ; ${scanProgressScript} {} ;"
	echo ""	
	echo "---------------------------------------------------------------------"
	echo "+ Fast TCP scan finished @" `date`
	echo "---------------------------------------------------------------------"
	"$pythonInterpreter" "$nmap2db" -i "$workingDir" -o "$database" -s nmap-sSV-Fast -a -O "$outputLog" -l "$logginglevel"
}

function execDefaultTCP() {
	echo 0 >  "$scanCounter"
	echo "---------------------------------------------------------------------"
	echo "+ Setting off default TCP scan @" `date`
	echo "---------------------------------------------------------------------"
	echo -n "Completed scans for: 0/${targetCount}"
	cat ${targetList} | xargs -P "$threads" -i /bin/bash -c "${scanScriptDirectory}scan_tcp_fast.sh -h {} -d -s ${speed} -o ${nmapOutputDir} -l ${loggingDir} ; ${scanProgressScript} {} ;"
	echo ""
	echo "---------------------------------------------------------------------"
	echo "+ Default TCP scan finished @" `date`
	echo "---------------------------------------------------------------------"
	"$pythonInterpreter" "$nmap2db" -i "$workingDir" -o "$database" -s nmap-sSV-Default -a -O "$outputLog" -l "$logginglevel"
	notify-send "Default TCP finished" 2> /dev/null
}

function execFastUDP() {	
	echo 0 >  "$scanCounter"
	echo "---------------------------------------------------------------------" 
	echo "+ Setting off fast UDP scan @" `date`
	echo "---------------------------------------------------------------------" 
	echo -n "Completed scans for: 0/${targetCount}"
	cat ${targetList} | xargs -P "$threads" -i /bin/bash -c "${scanScriptDirectory}scan_udp_fast.sh -h {} -s ${speed} -o ${nmapOutputDir} -l ${loggingDir} ; ${scanProgressScript} {} ;"
	echo ""
	echo "---------------------------------------------------------------------"
	echo "+ Fast UDP scan finished @" `date`
	echo "---------------------------------------------------------------------" 
	"$pythonInterpreter" "$nmap2db" -i "$workingDir" -o "$database" -s nmap-sUV-Fast -a -O "$outputLog" -l "$logginglevel"
	notify-send "Fast UDP finished" 2> /dev/null
}

function execFullTCP() {
	echo 0 >  "$scanCounter"
	echo "---------------------------------------------------------------------"
	echo "+ Setting off full TCP scan @" `date`
	echo "---------------------------------------------------------------------"
	echo -n "Completed scans for: 0/${targetCount}"
	if [ $noscript == "false" ]; then
		cat ${targetList} | xargs -P "$threads" -i /bin/bash -c "${scanScriptDirectory}scan_tcp.sh -h {} -p 1-65535 -s ${speed} -o ${nmapOutputDir} -l ${loggingDir} ; ${scanProgressScript} {} ;"
	else
		cat ${targetList} | xargs -P "$threads" -i /bin/bash -c "${scanScriptDirectory}scan_tcp_noscripts.sh -h {} -p 1-65535 -s ${speed} -o ${nmapOutputDir} -l ${loggingDir} ; ${scanProgressScript} {} ;"
	fi
	echo ""
	echo "---------------------------------------------------------------------"
	echo "+ Full TCP finished @" `date`
	echo "---------------------------------------------------------------------" 
	"$pythonInterpreter" "$nmap2db" -i "$workingDir" -o "$database" -s nmap-sSV-1-65535 -a -O "$outputLog" -l "$logginglevel"
	notify-send "Full TCP finished" 2>/dev/null
}

function execDefaultUDP() {
	echo 0 >  "$scanCounter"
	echo "---------------------------------------------------------------------"
	echo "+ Setting off default UDP scan @" `date`
	echo "---------------------------------------------------------------------"
	echo -n "Completed scans for: 0/${targetCount}"
	cat ${targetList} | xargs -P "$threads" -i /bin/bash -c "${scanScriptDirectory}scan_udp.sh -h {} -s ${speed} -o ${nmapOutputDir} -l ${loggingDir} ; ${scanProgressScript} {} ;"
	echo ""
	echo "---------------------------------------------------------------------"
	echo "+ Default UDP scan finished @" `date`
	echo "---------------------------------------------------------------------" 
	"$pythonInterpreter" "$nmap2db" -i "$workingDir" -o "$database" -s nmap-sUV-Default -a -O "$outputLog" -l "$logginglevel"
	notify-send "Default UDP finished" 2> /dev/null
}

function execShotgunTCP(){
	echo 0 >  "$scanCounter"	
	echo "---------------------------------------------------------------------"
        echo "+ Setting off shotgun TCP scan @ " `date` 
	echo "---------------------------------------------------------------------"
	echo -n "Completed scans for: 0/${targetCount}"
	xargs -a ${targetList} -P "$threads" -i /bin/bash -c "${scanScriptDirectory}scan_tcp.sh -h {} -p ${tcp_shotgun_ports} -s ${speed} -o ${nmapOutputDir} -l ${loggingDir} ; ${scanProgressScript} {} ;"
	echo ""
	echo "---------------------------------------------------------------------"
        echo "+ Shotgun TCP scan finished @ " `date` 
        echo "---------------------------------------------------------------------"
	"$pythonInterpreter" "$nmap2db" -i "$workingDir" -o "$database" -s "nmap-sSV-${tcp_shotgun_ports}" -a -O "$outputLog" -l "$logginglevel"
        notify-send "Shotgun TCP finished" 2> /dev/null
}

function execShotgunUDP(){
	echo 0 >  "$scanCounter"
	echo "---------------------------------------------------------------------"
        echo "+ Setting off shotgun UDP scan @" `date`
        echo "---------------------------------------------------------------------"
	echo -n "Completed scans for: 0/${targetCount}"
        xargs -a ${targetList} -P "$threads" -i /bin/bash -c "${scanScriptDirectory}scan_udp.sh -h {} -p ${udp_shotgun_ports} -s ${speed} -o ${nmapOutputDir} -l ${loggingDir} ; ${scanProgressScript} {} ;"
        echo ""
	echo "---------------------------------------------------------------------"
        echo "+ Shotgun UDP scan finished @" `date`
        echo "---------------------------------------------------------------------"
        "$pythonInterpreter" "$nmap2db" -i "$workingDir" -o "$database" -s "nmap-sUV-${udp_shotgun_ports}" -a -O "$outputLog" -l "$logginglevel"
        notify-send "Shotgun UDP finished" 2> /dev/null
}

function execPingSweep(){
	echo "---------------------------------------------------------------------"
	echo "+ Performing Ping Sweep (ARP Scan if on local network) @" `date`
	nmap -sP -n -iL ${targetList} -oA "$liveHostDir"targets.ping.result > "${loggingDir}/nmap.ping.sweep.log"	
	cat "$liveHostDir"targets.ping.result.nmap | grep "Nmap scan report" | awk '{print $5}' >> "$liveHostDir"hosts.alive
	echo "+ Completed Ping Sweep @" `date`
}

function execDNSSweep(){
	#echo "---------------------------------------------------------------------"
	echo "+ Performing DNS lookup @" `date`
	nmap -sL -iL ${targetList} -oA "$liveHostDir"targets.dns.result > "${loggingDir}/nmap.dns.sweep.log"
	cat "$liveHostDir"targets.dns.result.nmap | grep "Nmap scan report" | grep -r "(.*)" -o | sed 's/[()]//g' >> "$liveHostDir"hosts.alive	
	echo "+ Completed DNS Lookup @" `date`
}

function checkTargetsFile(){
	sort -o ${targetList} -u ${targetList}
	local targetCount=`cat ${targetList}| wc -l`	
	
	if [[ $targetCount -gt $scanLimit ]]; then
		echo "Currently, the maximum number of permitted targets is ${scanLimit}, but the target list contains ${targetCount}."
		echo "The limitation is imposed by filesystem subdirectory limits:"
		echo "   ext3 - 32000 (use 31998 as scan limit in config)"
		echo "   ext4 - 64000 (use 63998 as scan limit in config)"
		exit 1
	fi

	# already copied, we don't need a copy of the original again. Targets.original is used for job control, when pausing and restarting scans. You only want to cp it once, which will have the complete target list, and therefore you don't need to cp it again. 
	if [ -a "${workingDir}"targets.original ]; then
		echo "targets.original already exists - will not create new version"
	else
		cp "${targetList}" "${workingDir}"targets.original
	fi
}

echo "====================================================================="
echo "| METIS"
echo "| Author: A Hopkins"
echo "| Date: 16th August 2012"
echo "| Version 0.2"
echo "====================================================================="

if [ -z $1 ]; then
	echo
	echo "- No options have been specified"
	echo 
	exit 1
fi

while getopts "hp:i:T:s:ne:lPI:t:" key ; do

    case "${key}" in     
	h) usage;;
	p) threads=${OPTARG};;
	i) targetList=${OPTARG};;
	T) speed=${OPTARG};;
	s) scanOrder=${OPTARG};customScanModeSelected=true;;
	n) noscript=true;;
	e) escalateMode=${OPTARG};escalateModeSelected=true;;
	l) discoverModeSelected=true;;
	P) pluginsEnabled=true;;
	I) userSpecifiedInterface=${OPTARG};;
	t) pluginTimeout=${OPTARG};;
	*) exit;;
    esac
done

# handle non-getopt arguments, by removing the getopt arguments, and then getting a count
n=1 
while [ $# -gt 0 ]; do
	if [ $n -lt $OPTIND ];then
		#n=[[ n+1 ]] 
		((n++))
		shift
	else
		break;
	fi
done

if [ $# -gt 0 ]; then
	echo "- Option not supported"
	exit 1
fi

#######################################################################
# Input Validation
mkdir "$tempDir" 2> /dev/null

# if target list has not been specified and user isn't going to just scan the local subnet, then exit
if [ "${targetList}" == "" -a "$escalateModeSelected" != 'true' -a "$escalateMode" != 'local'  ]; then	
	echo "- A target list has not been specified in the metis.config file or at the command line"
	exit 1
# if the target list is empty, and the user isn't going to just scan the local subnet, then exit
elif [ ! -s "${targetList}" -a "$escalateModeSelected" != 'true' -a "$escalateMode" != 'local' ]; then
	echo "- Target file ${targetList} is empty"
        exit 1
# Check the number of hosts to be scanned.  There can be problems with some filesystems which only allow a certain number of subdirectories. This can cause problems, as the metis nmap directory creates a new directory for each IP in the list. 
elif [ "$escalateModeSelected" != 'true' -a "$escalateMode" != 'local' ]; then
	checkTargetsFile
fi

# if the plugin engine has been requested but no scans have been selected on the command line, then check for database
if [ "$pluginsEnabled" == 'true' -a "$scanOrder" == "" -a "$escalataMode" != 'true' ]; then
	if [ ! -f "$database" ]; then
		echo
		echo '- Plugin mode has been selected without a scanning mode but an existing database does not exist'
		echo
		exit 1
	fi
fi

# if we are doing a scan of the local subnet, and need to identify hosts through ARP, then we need to know the interface and check it is a valid
if [ "$escalateModeSelected" == 'true' -a "$escalateMode" == 'local' ]; then
	echo "Checking user specified interface - ${userSpecifiedInterface}"
	tail -n +3 /proc/net/dev | awk {'print $1'} | sed -r 's/:$//' > "$tempDir"interfaces.available
	interfaceFound='false'
	while read line; do
		if [ "${line}" == "$userSpecifiedInterface" ]; then
			echo "+ Interface ${line} found"
			interfaceFound='true'
		fi
	done < "$tempDir"interfaces.available
	
	if [ "$interfaceFound" == 'false' ]; then
		echo "- Interface ${userSpecifiedInterface} not found"
		exit 1
	fi
fi


if [ -n "$pluginTimeout" -a "$pluginsEnabled" == false ]; then
	echo "- Plugin timeout has been specified, but Plugin Mode hasn't been specified (-P)"
	exit 1
elif [ -n "$pluginTimeout" -a "$pluginsEnabled" == true ]; then
	# check whether timeout is a number
	if [[ ! "$pluginTimeout" =~ ^[0-9]+$ ]]; then 
		echo "- Plugin timeout specified is not an integer: ${pluginTimeout}"
		exit 1
	fi	
fi

# Perform some basic validation checks against the configuration items the user is most likely to change
"$METIS_HOME"utils/check-config.sh

# if there was an error in the config file then exit
if [ $? -eq 1 ];then
	echo "- Errors were identified in the configuration file. See above for more details."
	exit 1
fi

# End of input validation
###############################################################

#create output directories
mkdir "$loggingDir" 2> /dev/null
mkdir "$nmapOutputDir" 2> /dev/null
mkdir "$pluginDir" 2> /dev/null
mkdir "$summaryDir" 2> /dev/null
mkdir "$killedCommands" 2> /dev/null

#Create control file so scanning can start. If file exists scanning begins, otherwise Metis is put into pause mode. The check is in the scanscripts script files. 
# TO DO: NEED TO ADD SOME KIND OF ERROR HANDLING HERE, IN CASE IT WASNT POSSIBLE TO UPDATE FILE THEN THERE IS SOMETHING WRONG
touch "$controlFile"

# output the arguments used for the pentest
echo $@ >> "$summaryDir"options.used

# Create empty database
# This allows you to select any scan type to kick off first, and then just use append statements in code, rather than a series of if statements
# TO DO: AT THE MOMENT, WHILST THE PYTHON SCRIPT WILL RETURN ERROR MESSAGES. THESE ARE NOT HANDLED YET!!!!
"$pythonInterpreter" "$nmap2db" -e -o "$database" -O "$outputLog" -l "$logginglevel"


# TO DO: ALSO NEED A CHECK TO SEE IF THE FILE ACTUALLY EXISTS
echo "---------------------------------------------------------------------"
echo "+ Kicking off scan"
echo "+ Number of threads set at: ${threads}"
echo "+ Specified target file   : ${targetList}"

if [ "$escalateMode" != 'true' -a "$escalateMode" != 'local' ]; then
	targetCount=`cat ${targetList}| wc -l`	
	echo "+ Testing will be performed against ${targetCount} targets"
else
	echo "+ Performing ARP scan to determine live hosts"
fi

if [ "$escalateModeSelected" == 'true' ]; then
	if [ "$escalateMode" == 'shotgun' -o "$escalateMode" == 'fast' -o "$escalateMode" == 'default' -o "$escalateMode" == 'local' ]; then
		echo "+ Initiating Live Host Discovery"
		mkdir "$liveHostDir"
		
		if [ "$escalateMode" != 'local' ]; then
			execPingSweep
			execDNSSweep	
		else
			# perform an arp sweep and calculate the targets.txt from the results
			#arp-scan -I "${userSpecifiedInterface}" -l > "$tempDir"arp.results
			#cat "$tempDir"arp.results | tail -n +3 | head -n -3 | awk {'print $1'} | sort -u > "$targetList"
			"$pythonInterpreter" "$METIS_HOME"utils/local_subnet_ip_generator.py "$userSpecifiedInterface" > "$targetList"
			checkTargetsFile
			execPingSweep
			cp "$liveHostDir"hosts.alive "$targetList"
			targetCount=`cat ${targetList}| wc -l`	
			#cp "$targetList" "$liveHostDir"hosts.alive
			echo "+ Testing will be performed against ${targetCount} targets"
		fi
			
		if [ "$escalateMode" == "shotgun" ]; then
			execShotgunTCP
			execShotgunUDP
		elif [ "$escalateMode" == "fast" ]; then
			execFastTCP
			execShotgunUDP
		elif [ "$escalateMode" == "default" ]; then	
			execDefaultTCP
			execFastUDP
		fi
	
		sqlite3 "$database" 'select distinct ipaddress from services where state = "open"' >> "$liveHostDir"hosts.alive
		sort -u "$liveHostDir"hosts.alive > "$liveHostDir"hosts.alive.unique
		echo "---------------------------------------------------------------------"
		echo "+" `wc -l "$liveHostDir"hosts.alive.unique | awk {'print $1'}` "live hosts identified"
		echo "+ Unique list of live hosts has been output to ${liveHostDir}hosts.alive.unique"
		
		echo "+ Performing further scans against identified live hosts"
		targetList="$liveHostDir"hosts.alive.unique
		execFullTCP
		execDefaultUDP
	else
		echo "- An incorrect escalator mode has been selected - valid modes are: shotgun, fast, default, local"
		exit 1
	fi
elif [ "$customScanModeSelected" == "true" ]; then
	# prints the proposed scan engagement types, plus performs validation against user supplied input
	if [ "$escalateMode" == "none" ]; then
		# create an array which represents the different type of scan types supported
		scanType=([1]=execShotgunTCP [2]=execFastTCP [3]=execDefaultTCP [4]=execFullTCP [5]=execShotgunUDP [6]=execFastUDP [7]=execDefaultUDP [8]=execPingSweep [9]=execDNSSweep)
		# validation used to make sure user has entered a valid scan type
		validScanType=^[1-9]$
		echo "+ Performing the following scan types:"
		IFS=',' read -ra userSpecifiedOrder <<< "$scanOrder"
		for i in "${userSpecifiedOrder[@]}"; do
			if [[ "$i" =~ ${validScanType} ]]; then
				echo "	+ ${scanType[i]}" | sed 's/exec//'
			else
				echo "- Invalid Scan Type specified - ${i}"
				exit 1
			fi
		done
		#give the user a chance to review, what will be performed
		sleep 4
		# Initate the scans, using this method allows the order of scans to be kicked off according to how the user has specified using the -s option
		IFS=',' read -ra userSpecifiedOrder <<< "$scanOrder"
		for i in "${userSpecifiedOrder[@]}"; do
			"${scanType[i]}"
		done
	fi
elif [ "$discoverModeSelected" == "true" ]; then
	echo "+ Initiating Live Host Discovery"
	mkdir "$liveHostDir"
	execPingSweep
	execDNSSweep		
	execShotgunTCP
	execShotgunUDP
	sqlite3 "$database" 'select distinct ipaddress from services where state = "open"' >> "$liveHostDir"hosts.alive
	sort -u "$liveHostDir"hosts.alive > "$liveHostDir"hosts.alive.unique
	echo "---------------------------------------------------------------------"
	echo "+" `wc -l "$liveHostDir"hosts.alive.unique | awk {'print $1'}` "live hosts identified"
	echo "+ Unique list of live hosts has been output to ${liveHostDir}hosts.alive.unique"
fi

echo "---------------------------------------------------------------------"
echo "+ Port Scanning finished"
echo "---------------------------------------------------------------------"
echo 
echo "---------------------------------------------------------------------"
echo "+ Summarizing Dataset"
echo "---------------------------------------------------------------------"

echo "+ Converting database to CSV files"
echo "		+ Outputting host data to ${summaryDir}hosts.csv"
sqlite3 -csv -header "$database" 'select * from hosts' > "$summaryDir"hosts.csv
echo "		+ Outputting service data to ${summaryDir}services.csv"
sqlite3 -csv -header "$database" 'select * from services' > "$summaryDir"services.csv
echo "		+ Outputting NSE Script results to ${summaryDir}scriptResults.csv"
sqlite3 -csv -header "$database" 'select * from scriptResults' > "$summaryDir"scriptresults.csv
echo "+ Outputting identified interesting ports to "$summaryDir"interesting.services"
sqlite3 "$database" 'select distinct service from services where state = "open"' | sort -u > "$summaryDir"interesting.services 
echo "+ Outputting pentest statistics to "$summaryDir"open.port.statistics"
sqlite3 "$database" 'select ipaddress, count(port) from services where state = "open" group by ipaddress' > "$summaryDir"open.port.statistics
echo


if [ "$pluginsEnabled" == true ]; then 
	echo "---------------------------------------------------------------------"
	echo "+ Starting Plugins @" `date`
	echo "---------------------------------------------------------------------"
	for plugin in "$activePluginScripts"*
	do
		echo "+ Initiating ${plugin} @" `date`
		"$plugin" "$pluginTimeout" 
		echo "+ Completed ${plugin} @" `date`
	done
	echo "---------------------------------------------------------------------"
	echo "+ Plugins Completed @" `date`
	echo "---------------------------------------------------------------------"
fi



echo "---------------------------------------------------------------------"
echo "+ Cleaning up"
echo "---------------------------------------------------------------------"
echo "+ Removing ${tempDir}"
rm -rf "$tempDir"
echo "+ Cleaning empty plugin directories ${pluginDir}"
for plugin in "${pluginDir}"*
do 
	rmdir "$plugin" 2> /dev/null
done
echo "---------------------------------------------------------------------"
echo "+ End of pentest"
echo "---------------------------------------------------------------------"
